package api

import (
	"github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris/v12"
	"log"
	"main/store"
	"main/turkey"
	"time"
)

// UserHandler 这个结构引入IUserService方便在API（Controller）中调用Store（Model）中的函数
type UserHandler struct {
	service store.IUserService
}

// NewUserHandler 申请handler的时候将在API层要使用的东西传入
func NewUserHandler(service store.IUserService) *UserHandler {
	return &UserHandler{service: service}
}

func (u *UserHandler) Login(ctx iris.Context) {
	var loginReq store.UserLoginReq
	err := ctx.ReadJSON(&loginReq)
	if err != nil {
		log.Println(err)
		_, _ = ctx.JSON(Res(turkey.NotOK, err.Error(), iris.Map{}))
		return
	}
	if !loginReq.Valid() {
		_, _ = ctx.JSON(Res(turkey.NotOK, turkey.D___("json format invalid"), iris.Map{}))
		return
	}
	err = u.service.Login(loginReq)
	if err != nil {
		_, _ = ctx.JSON(Res(turkey.NotOK, err.Error(), iris.Map{}))
		return
	}

	token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": loginReq.Username,
		"exp":      time.Now().Add(10080 * time.Minute).Unix(),
	})
	object := iris.Map{}

	tokenString, _ := token.SignedString([]byte("WXZ"))

	object["jwt"] = tokenString

	_, _ = ctx.JSON(Res(turkey.OK, turkey.D___("login success"), object))

	return
}

func (u *UserHandler) UpdateUserProfile(ctx iris.Context) {
	var UpdateUserProfileReq store.UpdateUserProfileReq

	err := ctx.ReadJSON(&UpdateUserProfileReq)
	if err != nil {
		_, _ = ctx.JSON(Res(turkey.NotOK, turkey.D___("json format invalid"), iris.Map{}))
		return
	}
	//u.service.
}
